package com.ly.mpayment.rest.recharge;

import java.math.BigDecimal;
import java.util.List;

import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.rest.up.OrderHandler;
import com.ly.mpayment.rest.up.dongye.DongYeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.CookieRedis;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.downshopproduct.IDownShopProductService;
import com.ly.mpayment.persist.service.matchingstrategy.IMatchingStrategyService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.persist.service.upshoppro.IUpShopProService;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * 处理失败订单的第二次提交
 *
 *
 */
@Component
public class OrderThread {

	static Logger logger = Logger.getLogger(OrderThread.class);

	@Autowired
	IDownShopProductService productService;

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IUpShopProService upShopService;

	@Autowired
	IUporderService upOrderService;

	@Autowired
	IUpShopInfoService upShopInfoService;

	@Autowired
	ThreadPoolTaskExecutor taskExecutor;

	@Autowired
	IMatchingStrategyService matchStrategyService;

	@Autowired
	private OrderHandler orderHandler;

	/**
	 * 执行订单匹配选择
	 * @param flow
	 */
	public void orderHandle(DownRechargeFlow flow) {
		try {
			if (flow != null) {
				//检查产品是自动匹配还是手动匹配
				logger.info("execute:"+flow.getDowonphonenum());
				DownShopProduct downShop = flow.getDownShopProduct();
				if(downShop != null && downShop.getAuto() == Config.autoStrategy[0]){
					autoMatchOrder(flow);
				}else if (downShop != null && downShop.getAuto() == Config.autoStrategy[1]){
					manualMatchOrder(flow, 1,null);
				}else {
					matchOrder(flow,"产品配置错误");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage());
		}
	}

	/**
	 * 手动匹配 选取手动匹配产品中价格最低的优先处理
	 * 手动匹配有3种 匹配指定渠道
	 * 单面值匹配指定渠道
	 * 手动匹配多个渠道 依次失败 重提
	 * order 上一次订单的产品
	 * @param flow
	 */
	public void manualMatchOrder(DownRechargeFlow flow,Integer repeatNum,UpOrder order) {
		String upProducts = "";
		//如果当前渠道允许重提，则不检查产品
		if(order != null && orderHandler.checkNumDown(flow,"") > 1){
			UpShopInfo shop = upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
			if (shop == null) {
				logger.info("渠道商户异常:"+flow.getDowonphonenum());
				return;
			}
			//查询最后一次提交订单的商户id来判断是否是需要重复提交
			upProducts = this.upOrderService.findByFlowOrder(flow);
		}
		DownShopProduct downShop = flow.getDownShopProduct();
		//查找手动匹配的上游产品
		List<MatchingStrategy> matchingStrategy = this.matchStrategyService.findByDownUuid(flow.getUserFlow().getUseruuid(),downShop.getProvincialInformation().getProvinceuuid(),
				downShop.getOperators().getOperatoruid(),downShop.getBusinessType().getBusuuid(),downShop.getDownprouuid(),upProducts );
		if(CollectionUtils.isEmpty(matchingStrategy)){
			matchOrder(flow,"未找到手动产品配置");
			return;
		}
		//查询上游手动匹配的产品，唯一产品
		List<UpShopProduct> upShopProduct = upShopService.findOrderMatchManual(flow.getOperators(), flow.getProvince(),
				flow.getBusCode(), flow.getDiscountAmount(),
				flow.getDownShopProduct().getDownfacevalue(),flow.getDownShopProduct().getCityName(),matchingStrategy.get(0).getUpUser().getUseruuid());
		if (upShopProduct != null && !upShopProduct.isEmpty() && CookieRedis.get("manualMatchOrder").equals(Config.onOff)) {
			// 订单金额大于上游产品金额才执行
			if (flow.getDiscountAmount().compareTo(upShopProduct.get(0).getPrice().multiply(upShopProduct.get(0).getDiscount())) == 1) {
				// 检查最低金额 手动匹配也检查最低的 //第一次提交
				orderExecute(flow,upShopProduct.get(0),1);
				logger.info("手动执行匹配订单超额:".concat(flow.getDowonphonenum()));
			}else{
				logger.info("折扣异常:"+flow.getDowonphonenum()+","+upShopProduct.get(0).getDiscount()+","+flow.getDiscount());
				matchOrder(flow,"折扣异常:"+flow.getDowonphonenum()+","+upShopProduct.get(0).getDiscount()+","+flow.getDiscount());
			}
		} else if(upShopProduct != null && !upShopProduct.isEmpty()) {
			// 检查最低金额 手动匹配也检查最低的
			//第一次提交
			orderExecute(flow, upShopProduct.get(0),repeatNum);
			logger.info("手动执行匹配订单:".concat(flow.getDowonphonenum()));
		} else {
			matchOrder(flow,"未找到手动产品配置,请检查面值折扣");
		}
	}

	/**
	 * 修改订单状态为人工 并且更新msg备注
	 * @param flow
	 * @param msg
	 */
	private void matchOrder(DownRechargeFlow flow,String msg){
		DownRechargeFlow flow1 = this.flowService.findById(flow.getDownorderuuid());
		flow1.setRemark(msg);
		flow1.setStatus(Config.status[11]);
		this.flowService.updateDownrechargeflow(flow1);
	}

	/**
	 * 自动匹配 轮训 使用产品的地市 自动匹配地市 如果有地市则按地市查询
	 *
	 * @param flow
	 */
	private void autoMatchOrder(DownRechargeFlow flow) {
		// 检查自动订单匹配的产品 如果存在切换下一个
		// 自动匹配 每次匹配最低的价格 折扣之后匹配
		List<UpShopProduct> ups = upShopService.findOrderMatch(flow.getOperators(), flow.getProvince(),
				flow.getBusCode(), flow.getDiscountAmount(),
				flow.getDownShopProduct().getDownfacevalue(),flow.getDownShopProduct().getCityName());
		if (ups.isEmpty()) {
			// 没有找到上游对应的价格产品 则等待订单保留 待处理
			logger.info("未找到供货商产品配置:" + flow.getDowonphonenum());
			matchOrder(flow,"未找到供货商产品配置");
		} else {
			// 检查最低金额 手动匹配也检查最低的
			if (flow.getDiscountAmount().compareTo(ups.get(0).getPrice().multiply(ups.get(0).getDiscount())) == 1) {
				//第一次提交
				orderExecute(flow, ups.get(0),1);
			}else{
				logger.info("折扣异常:"+flow.getDowonphonenum()+","+ups.get(0).getDiscount()+","+flow.getDiscount());
				matchOrder(flow,"折扣异常:"+flow.getDowonphonenum()+","+ups.get(0).getDiscount()+","+flow.getDiscount());
			}
		}
	}

	/**
	 * 先查询改订单是否存在 如果存在则更新， 否则添加
	 *
	 * @param flow
	 * @param upShop
	 */
	@SuppressWarnings("unused")
	public void orderExecute(DownRechargeFlow flow, UpShopProduct upShop,Integer repeatNum) {
		//供货商充值金额检查
		if (CookieRedis.get("upPriceCheck").equals(Config.onOff)) {
			if(!(upShop.getPrice().multiply(upShop.getDiscount()).compareTo(flow.getDiscountAmount()) == -1 ||
					upShop.getPrice().multiply(upShop.getDiscount()).compareTo(flow.getDiscountAmount()) == 0)){
				matchOrder(flow,"产品价格匹配错误");
				logger.info("orderExecute产品价格匹配错误:" + flow.getDowonphonenum());
				return ;
			}
		}
		// 检查订单是否存在 充值中的订单
		UpOrder order = upOrderService.findByDownFlowRechare(flow.getDownorderuuid());
		if (order == null) {
			UpShopInfo shop = upShopInfoService.findByUserId(upShop.getUser().getUseruuid());
			if (shop == null) {
				logger.info("渠道商户异常:"+flow.getDowonphonenum());
				return;
			}
			order = new UpOrder();
			order.setDownRechargeFlow(flow);
			order.setProvince(flow.getProvince());
			order.setCityName(flow.getCityName());
			order.setRechargeamount(upShop.getPrice());
			order.setRemark(flow.getRemark());
			//检查渠道是否压单
			if(shop.getPressOrder()){
				order.setStatus(Config.status[10]);
			}else{
				//检查产品是否压单
				if(upShop.getPressOrder()){
					order.setStatus(Config.status[10]);
				}else{
					order.setStatus(Config.status[0]);
				}
			}
			//工号
			if(shop.getShopnum().equals(Config.qinghaijb) || shop.getShopnum().equals(Config.hunanjob) ){
				order.setStatus(Config.status[5]);
			}
			order.setUpphonenum(flow.getDowonphonenum());
			order.setUpShopPro(upShop);
			order.setUserOrder(upShop.getUser());
			order.setCallBack(Config.callStatus[0]);
			order.setSendStatus(Config.sendStatus[1]);
			order.setDiscount(upShop.getDiscount());
			order.setOperators(flow.getOperators());
			order.setOperatorname(flow.getOperatorname());
			//检查渠道重复提交是否开启 0 不重复提交 大于0则失败重复提交
			order.setStatusremark(shop.getRepeatNum() > 0 ?  Config.orderStatus[1] :  Config.orderStatus[0]);
			order.setRepeatNum(repeatNum);
			order.setUpOrderId("");
			order.setChildOrder("");
			order.setUprechargenum(flow.getDownrechargenum());
			order.setDiscountAmount(upShop.getPrice().multiply(BigDecimal.valueOf(order.getUprechargenum())).multiply(upShop.getDiscount()));
			order.setName(flow.getName());
			order.setAreaName(flow.getAreaName());
			order.setSourceIp(flow.getSourceIp());
			order.setRechargeType(flow.getRechargeType());
			order.setServer(flow.getServer());
			if (flow != null) {
				order.setDownShopName(flow.getUserFlow().getUsername());
			}

			if (shop != null && flow.getRechargeamount().compareTo(order.getRechargeamount()) == 0) {
				order = upOrderService.saveOrder(order);
				if(order != null && !shop.getPressOrder() && !upShop.getPressOrder()){
					// 保存订单成功后 发送上游充值请求
					orderHandler.commitOrder(order,shop);
				}else{
					logger.info("压单:"+flow.getDowonphonenum());
				}
				return;
			} else {
				matchOrder(flow,"供货商渠道信息错误");
				logger.info("orderExecute供货商渠道信息错误:" + flow.getDownorderuuid()+",flow:"+ flow.getRechargeamount()+",order:"+order.getRechargeamount());
			}
		}else{
			logger.info("上游订单已经存在:"+flow.getDowonphonenum());
		}
		return;
	}



}
